package com.zezheng.qian.project.anxinsign.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zezheng.qian.framework.config.RuoYiConfig;
import com.zezheng.qian.project.anxinsign.dto.Head;
import com.zezheng.qian.project.anxinsign.dto.response.ResponseDTO;
import com.zezheng.qian.project.anxinsign.service.AnxinService;
import okhttp3.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class AnxinServiceImpl implements AnxinService {

    @Override
    public <R, T> void doRequest(String txCode, Object requestData, Class<T> clazz, DeferredResult<R> deferredResult) {
        try {
            String url = String.format("https://%s:%s/FEP/platId/%s/txCode/%s/transaction", RuoYiConfig.getAnxinIp(), RuoYiConfig.getAnxinPort(), RuoYiConfig.getAnxinPlatId(), txCode);

            OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody requestBody = RequestBody.create(JSON, String.valueOf(requestData));
            Request request = new Request.Builder().url(url).post(requestBody).build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println("Fail");
                    dealResponseFailure(0, "", deferredResult);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        Head head;
                        JSONObject root = JSONObject.parseObject(response.body().string());
                        JSONArray data = root.getJSONArray("data");

                        if (data != null && data.size() > 0) {
                            root = data.getJSONObject(0);
                        }
                        T result = root.toJavaObject(clazz);
                        head = root.toJavaObject(Head.class);
                        deferredResult.setResult((R) ResponseDTO.success(head, result, data, requestData, url));
                    } catch (Exception e) {
                        returnErrorResult(deferredResult, "-1", "", "-1", "处理响应报文异常");
                    }
                }
            });
        } catch (Exception e) {
            returnErrorResult(deferredResult, "-1", "", "-1", "请求异常");
        }
    }

    private <R> void dealResponseFailure(int code, String responseBody, DeferredResult<R> deferredResult) {
        String msg = "响应报文异常";
        if (code == 404) {
            msg = "功能号尚未开通";
        } else if (code == 401) {
            msg = "OAuth 认证失败";
        }

        try {
            JSONObject root = JSONObject.parseObject(responseBody);
            Head Head = root.toJavaObject(Head.class);
            deferredResult.setResult((R) ResponseDTO.success(Head, null));
        } catch (Exception e) {
            returnErrorResult(deferredResult, "1", msg, String.valueOf(code), msg);
        }
    }

    private <R> void returnErrorResult(DeferredResult<R> deferredResult, String retCode, String retMessage, String errorCode, String errorMessage) {
        Head Head = new Head();
        Head.setRetCode(retCode);
        Head.setRetMessage(retMessage);
        Head.setErrorCode(errorCode);
        Head.setErrorMessage(errorMessage);
        deferredResult.setResult((R) ResponseDTO.success(Head, null));
    }
}
